﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.IO;
using System.Runtime.Serialization;

namespace agilecards.Model
{
    public class IsolatedStorageCardPersistor : ICardCollectionPersistor
    {
        public IsolatedStorageCardPersistor(DtoConverter dtoConverter)
        {
            _dtoConverter = dtoConverter;
        }

        #region ICardCollectionPersistor Members

        public void Save(ICardCollection collection)
        {
            CardCollectionDto collectionDto = _dtoConverter.ConvertToDto(collection);
            SaveData<CardCollectionDto>(collectionDto, collectionDto.Id);
        }

        public ICardCollection Load(string boardId)
        {
            if (!IsolatedStorageFile.GetUserStoreForApplication().FileExists(boardId))
            {
                return null;
            }

            CardCollectionDto collectionDto = LoadData<CardCollectionDto>(boardId);
            ICardCollection cardCollection = _dtoConverter.ConvertFromDto(collectionDto);
            return cardCollection;
        }

        private void SaveData<T>(T dataToSave, string fileName)
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream stream = store.CreateFile(fileName);
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(stream, dataToSave);
                stream.Close();
            }
        }

        private T LoadData<T>(string fileName)
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Open);
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                T result = (T)serializer.ReadObject(stream);
                stream.Close();
                return result;
            }
        }
        

        #endregion

        private readonly DtoConverter _dtoConverter;
    }
}
